/**
 \* Created with IntelliJ IDEA.
 \* User: 彭诗杰
 \* Date: 2018/8/6 14:35
 \* Description:  大气类state
 \*/

import API from "../../api/api_air";
import util from '../../common/util';

const state = {
  airFactors:[],
  // 当前大气污染源系统，包括factors监测因子以及factor.latest最新数据
  airSystem: {},
  // 当天全部实时数据
  airPresents: [],
  // 当天分页实时数据
  airPresentPagingList: [],
  // 历史数据
  airHistoryList: [],

  pagination: {
    page: 0,
    limit: 10,
    total: 100,
  },
};

const getters = {
  airSystem: state => {
    return state.airSystem;
  },
  airHistories: state => {
    return state.airHistoryList;
  },
  airPresents: state => {
    return state.airPresents;
  },
  airPresentPaging: state => {
    return state.airPresentPagingList
  },
  airFactors: state => {
    return state.airFactors;
  }
};

const actions = {

  /**
   * 不分页获取大气单指标历史数据
   * @param commit
   * @param state
   * @param params
   * @returns {Promise<any>}
   */
  getAirFactorHistoriesNoPagingAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getAirHistoriesNoPaging(params).then(result => {
        resolve(result);
      }, err => {
        reject(err);
      }).catch(error => {
        reject(error);
      })
    })
  },

  /**
   * 获取当日指标实时数据
   * @param commit
   * @param state
   * @param params
   * @returns {Promise<any>}
   */
  getAirPresentListAct({commit, state}, params) {
    return new Promise(async (resolve, reject) => {
      if (!params.factors) {
        reject('当前集成商系统factors为空！');
      }
      let allRows = [];
      for (let factor of params.factors) {
        try {
          let factorParams = {
            airId: params.airId,
            systemCode: params.systemCode,
            factorCode: factor.code,
            dateStart: params.dateStart,
            dateEnd: params.dateEnd
          };
          let singleValues = await API.getAirHistoriesNoPaging(factorParams);
          let data = singleValues.map(item => item.value);
          let times = singleValues.map(item => item.time);
          allRows.push({factorName: factor.name, data: data, time: times})
        } catch (e) {
          reject(e)
        }
      }
      commit('setAirPresentList', allRows);
      resolve();
    })
  },

  /**
   * 按指标获取后台当日实时数据并组装成el-table格式
   *
   * @param commit
   * @param state
   * @param params
   * @returns {Promise<any>}
   */
  getAirPresentPagingAct({commit, state}, params) {
    return new Promise(async (resolve, reject) => {
      let airHistories = [];
      let total = 0;
      try {
        if (params.factors) {
          for (let factor of params.factors) {
            let factorParams = {
              airId: params.airId,
              systemCode: params.systemCode,
              factorCode: factor.code,
              dateStart: params.dateStart,
              dateEnd: params.dateEnd,
              page: params.pagination.page,
              limit: params.pagination.limit
            };
            let factorHistories = await API.getAirFactorHistoryValues(factorParams);
            let formatFactorHistories = factorHistories.factorValueVos;
            total = factorHistories.total;
            formatFactorHistories.forEach(formatFactorHistory => {
              airHistories.push(formatFactorHistory);
            });
          }
        }
      } catch (err) {
        reject(err)
      }
      let groupedByTime = util.groupArray(airHistories, 'time');
      console.log('groupedByTime', groupedByTime)
      // 将按时间戳分好的数据按factorId进行赋值
      let allRows = [];
      groupedByTime.forEach(groupedTimeItem => {
        let eachRow = [];
        eachRow.time = groupedTimeItem.initial;
        eachRow.data = [];
        params.factors.forEach(factor => {
          groupedTimeItem.list.forEach(item => {
            if (factor.id === item.factorId) {
              let eachRowItem = {
                id: item.id,
                name: factor.code,
                value: item.value,
                outRange: item.outRange
              };
              eachRow.data.push(eachRowItem);
            }
          })
        });
        allRows.push(eachRow);
        //console.log(allRows)
      });

      let pagination = {
        total: total,
        page: params.pagination.page,
        limit: params.pagination.limit,
      };
      commit('setAirPresentPageList', allRows);
      resolve(pagination);
    })
  },

  /**
   * 按指标获取后台历史数据并组装成el-table格式，草特么的难写
   * @param commit
   * @param state
   * @param params
   * @returns {Promise}
   */
  getAirHistoryListAct({commit, state}, params) {
    return new Promise(async (resolve, reject) => {
      let airHistories = [];
      let total = 0;
      try {
        if (params.factors) {
          for (let factor of params.factors) {
            let factorParams = {
              airId: params.airId,
              systemCode: params.systemCode,
              factorCode: factor.code,
              dateStart: params.dateStart,
              dateEnd: params.dateEnd,
              page: params.pagination.page,
              limit: params.pagination.limit
            };
            let factorHistories = await API.getAirFactorHistoryValues(factorParams);
            let formatFactorHistories = factorHistories.factorValueVos;
            total = factorHistories.total;
            formatFactorHistories.forEach(formatFactorHistory => {
              airHistories.push(formatFactorHistory);
            });
          }
        }
      } catch (err) {
        reject(err)
      }
      let groupedByTime = util.groupArray(airHistories, 'time');
      //commit('setSewageHistoriesWithRange', groupedByTime);
      //console.log(groupedByTime);
      // 将按时间戳分好的数据按factorId进行赋值
      let allRows = [];
      groupedByTime.forEach(groupedTimeItem => {
        let eachRow = [];
        eachRow.time = groupedTimeItem.initial;
        eachRow.data = [];
        params.factors.forEach(factor => {
          groupedTimeItem.list.forEach(item => {
            if (factor.id === item.factorId) {
              let eachRowItem = {
                id: item.id,
                name: factor.code,
                value: item.value,
                outRange: item.outRange
              };
              eachRow.data.push(eachRowItem);
            }
          })
        });
        allRows.push(eachRow);
      });
      let pagination = {
        total: total,
        page: params.pagination.page,
        limit: params.pagination.limit,
      };

      commit('setAirHistoryList', allRows);
      resolve(pagination);
    });
  },

  getAirSystemsAct({commit, state}, area) {
    return new Promise((resolve, reject) => {
      API.getAirSystems(area.airId).then(result => {
        resolve(result);
      }, err => {
        reject(err);
      }).catch(error => {
        reject(error);
      })
    })
  },

  getAirSystemFactorsAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getAirFactors(params).then(factors => {
        resolve(factors);
      }, err => {
        reject(err);
      }).catch(error => {
        reject(error);
      })
    })
  },

  getAirFactorLatestValueAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getAirLatestValue(params).then(result => {
        resolve(result);
      }).catch(error => {
        reject(error);
      })
    })
  },

  setAirHistoryList({commit, state}, data) {
    commit('setAirPresentList', data)
  },
  setAirFactorsAct({commit, state}, data) {
    commit('setAirFactors', data)
  },

  setAirSystemAct({commit, state}, system) {
    commit('setAirSystem', system);
  }
};

const mutations = {
  setAirPresentList(state, entity) {
    state.airPresents = entity;
  },
  setAirHistoryList(state, entity) {
    state.airHistoryList = entity;
  },

  setAirPresentPageList(state, entity) {
    state.airPresentPagingList = entity;
  },

  setAirSystem(state, entity) {
    state.airSystem = entity;
  },

  setAirFactors(state, entity){
    state.airFactors = entity;
  }
};

export default {
  state,
  getters,
  actions,
  mutations
}
